//
//  JCUpdateMemberViewController.swift
//  JChat
//
//  Created by JIGUANG on 2017/5/11.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import JMessage

class JCUpdateMemberViewController: BaseViewController {
    
    /// 选择成员
    typealias addUserClosure = (_ users: [JMSGUser]) -> Swift.Void
    
    var isAddMember = true
    var group: JMSGGroup?
    var currentUser: JMSGUser?
    
    private var updateMemberType: UpdateMemberType = .club
    
    private var addUserCallback: addUserClosure?

    override func viewDidLoad() {
        super.viewDidLoad()
        _init()
    }
    
    convenience init(updateMemberType: UpdateMemberType, joinUsers: [JMSGUser] = [], complete: addUserClosure?) {
        self.init()
        self.updateMemberType = updateMemberType
        self.addUserCallback = complete
        self.joinUsers = joinUsers
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if selectUsers.count == 0 {
            confirm.alpha = 0.5
            navigationController?.navigationItem.rightBarButtonItem?.isEnabled = false
        }
    }

    private var topOffset: CGFloat {
        return 0
    }

    fileprivate lazy var toolView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: 56))
    fileprivate var tableView: UITableView = UITableView(frame: .zero, style: .grouped)
    fileprivate var collectionView: UICollectionView!
    fileprivate lazy var searchBar: UISearchBar = UISearchBar.default
    fileprivate lazy var confirm = UIButton(frame: CGRect(x: 0, y: 0, width: 120, height: 28))
    
    fileprivate lazy var users: [JMSGUser] = []
    /// 已经加入俱乐部活动的成员
    fileprivate lazy var joinUsers: [JMSGUser] = []
    fileprivate lazy var keys: [String] = []
    fileprivate lazy var data: Dictionary<String, [JMSGUser]> = Dictionary()
    
    fileprivate lazy var filteredUsersArray: [JMSGUser] = []
    fileprivate lazy var selectUsers: [JMSGUser] = []
    fileprivate var searchUser: JMSGUser?
    fileprivate var members: [JMSGUser]?
    
    fileprivate let toolViewHeight: CGFloat = 56
    
    fileprivate lazy var tipsView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: self.topOffset + 31 + 5, width: self.view.width, height: self.view.height - 31 - self.topOffset - 5))
        view.backgroundColor = UIColor.theme.background
        let tips = UILabel(frame: CGRect(x: 0, y: 0, width: view.width, height: 50))
        tips.font = UIFont.systemFont(ofSize: 16)
        tips.textColor = UIColor(hex: 0x999999)
        tips.textAlignment = .center
        tips.text = "未搜索到用户"
        view.addSubview(tips)
        view.isHidden = true
        return view
    }()
    
    private func _init() {
        view.backgroundColor = UIColor.theme.background
        //automaticallyAdjustsScrollViewInsets = false
        self.title = "编辑"
        if isAddMember {
            if self.updateMemberType == .clubActivity {
//                self.title = "添加活动成员"
                members = self.joinUsers
            } else {
//                self.title = "添加成员"
                members = group?.memberArray()
            }
        } else {
            self.title = "发起群聊"
        }
        
        view.addSubview(toolView)
        
        toolView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(toolViewHeight)
        }
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = .onDrag
        tableView.sectionIndexColor = UIColor(hex: 0x2dd0cf)
        tableView.sectionIndexBackgroundColor = .clear
        tableView.register(JCSelectMemberCell.self, forCellReuseIdentifier: "JCSelectMemberCell")
        //tableView.frame = CGRect(x: 0, y: toolView.height, width: view.width, height: view.height - toolView.height - NavigationBarHeight - StatusBarHeight)
        tableView.backgroundColor = UIColor.theme.background
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(toolView.snp.bottom)
        }
        
        view.addSubview(tipsView)
        
        tipsView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(toolView.snp.bottom).offset(20)
        }
        
        _classify([], isFrist: true)
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectionView.backgroundColor = UIColor.theme.background
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(JCUpdateMemberCell.self, forCellWithReuseIdentifier: "JCUpdateMemberCell")
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 11, bottom: 0, right: 11)
        
        searchBar.frame = CGRect(x: 15, y: 11, width: toolView.width - 30, height: 32)
        searchBar.delegate = self
        searchBar.placeholder = "搜索"
        searchBar.barStyle = .blackTranslucent
        searchBar.barTintColor = UIColor.theme.background
        searchBar.inputView?.backgroundColor = UIColor.theme.background
        
        
        searchBar.layer.borderColor = UIColor.theme.background.cgColor
        searchBar.layer.borderWidth = 1
        searchBar.layer.masksToBounds = true
        
        searchBar.backgroundColor = .black
        searchBar.backgroundImage = UIImage(color: UIColor.theme.background, size: CGSize(width: 414, height: 32))
        searchBar.setSearchFieldBackgroundImage(UIImage(color: UIColor.theme.background, size: CGSize(width: 414, height: 32)), for: .normal)
        
        toolView.backgroundColor = UIColor.theme.background
//        toolView.backgroundColor = UIColor.red
        toolView.addSubview(searchBar)
        toolView.addSubview(collectionView)
        
        toolView.addSubview(lineView)
        
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.top.equalTo(searchBar.snp.bottom).offset(3)
            make.height.equalTo(1)
        }
        
        
        collectionView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
            make.width.lessThanOrEqualTo(0)
        }
        
        searchBar.snp.makeConstraints { (make) in
            make.height.equalTo(32)
            make.left.equalTo(collectionView.snp.right).offset(11)
            make.right.equalToSuperview().offset(-11)
            make.centerY.equalToSuperview()
            make.width.lessThanOrEqualTo(100).priority(.high)
        }
        
        _setupNavigation()
    }
    
    private func _setupNavigation() {
//        confirm.addTarget(self, action: #selector(_clickNavRightButton(_:)), for: .touchUpInside)
//        confirm.setTitle("确定", for: .normal)
//        confirm.titleLabel?.font = UIFont.systemFont(ofSize: 15)
//        confirm.contentHorizontalAlignment = .right
//        let item = UIBarButtonItem(customView: confirm)
//        navigationItem.rightBarButtonItem =  item
        
        view.addSubview(commitButton)
        
        commitButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.equalTo(210)
            make.height.equalTo(44)
            make.bottom.equalToSuperview().offset(-ScreenBottomExtraOffset)
        }
    }
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        return v
    }()
    
    lazy var commitButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("确定添加", for: .normal)
        btn.setTitleColor(UIColor.text.x161616, for: .normal)
        btn.backgroundColor = UIColor.redpack.x5d5d5d
        btn.isUserInteractionEnabled = false
        btn.layer.cornerRadius = 22
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(_clickNavRightButton(_:)), for: .touchUpInside)
        return btn
    }()
    
    private func friendsList() {
        JMSGFriendManager.getFriendList { (result, error) in
            if error == nil {
                self.users.removeAll()
                self.keys.removeAll()
                self.data.removeAll()
                for item in result as! [JMSGUser] {
                    if let currentUser = self.currentUser {
                        if item.username == currentUser.username {
                            continue
                        }
                    }
                    self.users.append(item)
                    var key = item.displayName().firstCharacter()
                    if !key.isLetterOrNum() {
                        key = "#"
                    }
                    var array = self.data[key]
                    if array == nil {
                        array = [item]
                    } else {
                        array?.append(item)
                    }
                    if !self.keys.contains(key) {
                        self.keys.append(key)
                    }
                    
                    self.data[key] = array
                }
                self.filteredUsersArray = self.users
                self.keys = self.keys.sortedKeys()
                self.tableView.reloadData()
                self.collectionView.reloadData()
            }
        }
    }
    
    private func groupList() {
        group?.memberInfoList({ (result, error) in
            if error == nil {
                if let userInfos: [JMSGGroupMemberInfo] = result as? [JMSGGroupMemberInfo] {
                    let r : [JMSGUser?] = userInfos.map { (info) -> JMSGUser? in
                        return info.user
                    }
                    self.users.removeAll()
                    self.keys.removeAll()
                    self.data.removeAll()
                    if let result = r as? [JMSGUser] {
                        for item in result {
                            if let currentUser = self.currentUser {
                                if item.username == currentUser.username {
                                    continue
                                }
                            }
                            self.users.append(item)
                            var key = item.displayName().firstCharacter()
                            if !key.isLetterOrNum() {
                                key = "#"
                            }
                            var array = self.data[key]
                            if array == nil {
                                array = [item]
                            } else {
                                array?.append(item)
                            }
                            if !self.keys.contains(key) {
                                self.keys.append(key)
                            }
                            
                            self.data[key] = array
                        }
                        self.filteredUsersArray = self.users
                        self.keys = self.keys.sortedKeys()
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                            self.collectionView.reloadData()
                        }
                    }
                }
            }
        })
    }
    
    fileprivate func _classify(_ users: [JMSGUser], isFrist: Bool = false) {
        
        if users.count > 0 {
            tipsView.isHidden = true
        }
        
        if isFrist {
            if self.updateMemberType == .club {
                friendsList()
            } else if self.updateMemberType == .clubActivity {
                groupList()
            }
            
        } else {
            filteredUsersArray = self.users
            keys.removeAll()
            data.removeAll()
            for item in users {
                var key = item.displayName().firstCharacter()
                if !key.isLetterOrNum() {
                    key = "#"
                }
                var array = data[key]
                if array == nil {
                    array = [item]
                } else {
                    array?.append(item)
                }
                if !keys.contains(key) {
                    keys.append(key)
                }
                
                data[key] = array
            }
            keys = keys.sortedKeys()
            tableView.reloadData()
            collectionView.reloadData()
        }
    }
    
    fileprivate func _removeUser(_ user: JMSGUser) {
        selectUsers = selectUsers.filter({ (u) -> Bool in
            u.username != user.username || u.appKey != user.appKey
        })
    }
    
    fileprivate func _reloadCollectionView() {
        if #available(iOS 13.0, *) {
            searchBar.searchTextField.leftViewMode =  selectUsers.count > 0 ? .never : .always
        } else {
            // Fallback on earlier versions
        }
        lineView.isHidden = selectUsers.count > 0
        if selectUsers.count > 0 {
            searchBar.snp.updateConstraints { (make) in
                make.left.equalTo(collectionView.snp.right).offset(-35)
            }
            collectionView.snp.updateConstraints { (make) in
                make.width.lessThanOrEqualTo(50 * (selectUsers.count > 6 ? 6 : selectUsers.count) +  11 * 2)
            }
//            confirm.alpha = 1.0
//            confirm.setTitle("确定(\(selectUsers.count))", for: .normal)
//            navigationController?.navigationItem.rightBarButtonItem?.isEnabled = true
            commitButton.isUserInteractionEnabled = true
            commitButton.backgroundColor = UIColor.theme.main
        } else {
            collectionView.snp.updateConstraints { (make) in
                make.width.lessThanOrEqualTo(0)
            }
            searchBar.snp.updateConstraints { (make) in
                make.left.equalTo(collectionView.snp.right).offset(0)
            }
//            confirm.alpha = 0.5
//            confirm.setTitle("确定", for: .normal)
//            navigationController?.navigationItem.rightBarButtonItem?.isEnabled = false
            commitButton.isUserInteractionEnabled = false
            commitButton.backgroundColor = UIColor.redpack.x5d5d5d
        }
        
        collectionView.reloadData()
    }
    
    @objc func _clickNavRightButton(_ sender: UIButton) {
        if selectUsers.count == 0 {
            return
        }
        var userNames: [String] = []
        for item in selectUsers {
            userNames.append(item.username)
        }
        
        /// 添加俱乐部活动成员
        if self.updateMemberType == .clubActivity {
            self.addUserCallback?(selectUsers)
            self.navigationController?.popViewController(animated: true)
            return
        }
        
        if isAddMember {
            MBProgressHUD_JChat.showMessage(message: "添加中...", toView: view)
            group?.addMembers(withUsernameArray: userNames, completionHandler: { (result, error) in
                MBProgressHUD_JChat.hide(forView: self.view, animated: true)
                if error == nil {
                    /// 添加俱乐部成员
                    self.addUserCallback?(self.selectUsers)
                    NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateGroupInfo), object: nil)
                    self.navigationController?.popViewController(animated: true)
                } else {
                    MBProgressHUD_JChat.show(text: "添加失败，请重试", view: self.view)
                }
            })
        
        } else {
            if currentUser != nil {
                userNames.insert((currentUser?.username)!, at: 0)
            }
            MBProgressHUD_JChat.showMessage(message: "创建中...", toView: view)
            JMSGGroup.createGroup(withName: nil, desc: nil, memberArray: userNames, completionHandler: { (result, error) in
                MBProgressHUD_JChat.hide(forView: self.view, animated: true)
                if error == nil {
                    for vc in (self.navigationController?.viewControllers)! {
                        if vc is JCConversationListViewController {
                            self.navigationController?.popToViewController(vc, animated: true)
                            let group = result as! JMSGGroup
                            JMSGConversation.createGroupConversation(withGroupId: group.gid, completionHandler: { (result, error) in
                                let conv = JMSGConversation.groupConversation(withGroupId: group.gid)
                                let chatVC = JCChatViewController(conversation: conv!)
                                vc.navigationController?.pushViewController(chatVC, animated: true)
                            })
                        }
                    }
                    
                } else {
                    MBProgressHUD_JChat.show(text: "创建失败，请重试", view: self.view)
                }
            })
        }
    }
    
    fileprivate func filter(_ searchString: String) {
        if searchString.isEmpty || searchString == "" {
            _classify(users)
            return
        }
        let searchString = searchString.uppercased()
        filteredUsersArray = _JCFilterUsers(users: users, string: searchString)
        _classify(filteredUsersArray)
    }
}

//Mark: -
extension JCUpdateMemberViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if filteredUsersArray.count > 0 {
            return keys.count
        }
        return 0
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data[keys[section]]!.count
    }
    
//    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
//        return keys[section]
//    }
    
//    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
//        return keys
//    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70 //55
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
//        if section == 0 {
//            return 30
//        }
//        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "JCSelectMemberCell", for: indexPath)
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let cell = cell as? JCSelectMemberCell else {
            return
        }
        let user = data[keys[indexPath.section]]?[indexPath.row]
        cell.bindDate(user!)
        if let members = members {
            if members.contains(where: { (u) -> Bool in
                return u.username == user?.username && u.appKey == user?.appKey
            }) {
                cell.selectIcon = UIImage.loadImage("com_icon_isSelect")
                return
            }
        }
        if selectUsers.contains(where: { (u) -> Bool in
            return u.username == user?.username && u.appKey == user?.appKey
        })  {
            cell.selectIcon = UIImage(named: "icon_select")
        } else {
            cell.selectIcon = UIImage(named: "icon_unselect")
        }
        
        cell.hiddenLine = data.count == 1
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard let cell = tableView.cellForRow(at: indexPath) as? JCSelectMemberCell else {
            return
        }
        let user = data[keys[indexPath.section]]?[indexPath.row]
        if members != nil {
            if (members?.contains(where: { (u) -> Bool in
                return u.username == user?.username && u.appKey == user?.appKey
            }))! {
                return
            }
        }
        if selectUsers.contains(where: { (u) -> Bool in
            return u.username == user?.username && u.appKey == user?.appKey
        })  {
            // remove
            cell.selectIcon = UIImage(named: "icon_unselect")
            _removeUser(user!)
            _reloadCollectionView()
        } else {
            selectUsers.append(user!)
            cell.selectIcon = UIImage(named: "icon_select")
            _reloadCollectionView()
        }
        if selectUsers.count > 0 {
            collectionView.scrollToItem(at: IndexPath(row: selectUsers.count - 1, section: 0), at: .right, animated: false)
        }
    }
}

extension JCUpdateMemberViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return selectUsers.count
    }
    
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        return CGSize(width: 44, height: 44)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: "JCUpdateMemberCell", for: indexPath)
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let cell = cell as? JCUpdateMemberCell else {
            return
        }
        
        cell.bindDate(user: selectUsers[indexPath.row])
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectUsers.remove(at: indexPath.row)
        tableView.reloadData()
        _reloadCollectionView()
    }
}

extension JCUpdateMemberViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        filter(searchText)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        // 搜索非好友
        let searchText = searchBar.text!
        JMSGUser.userInfoArray(withUsernameArray: [searchText]) { (result, error) in
            if error == nil {
                let users = result as! [JMSGUser]
                self.searchUser = users.first
                self._classify([self.searchUser!])
                self.tipsView.isHidden = true
            } else {
                // 未查询到该用户的信息
                self.tipsView.isHidden = false
            }
        }
    }
}


